package com.wryyyyy.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.influxdb.query.FluxRecord;
import com.influxdb.query.FluxTable;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class FluxResult {
    public static <T> T toBean(List<FluxTable> tables, Class<T> beanClass) {
        JSONObject jsonObject = new JSONObject();

        for (FluxTable fluxTable : tables) {
            List<FluxRecord> records = fluxTable.getRecords();
            for (FluxRecord fluxRecord : records) {
                jsonObject.putOnce(fluxRecord.getField(), fluxRecord.getValue());
            }
        }

        String jsonString = JSONUtil.toJsonStr(jsonObject);

        return JSONUtil.toBean(jsonString, beanClass);
    }

    public static Double toPercentage(List<FluxTable> tables) {
        String passing = "0";
        String total = "1";

        for (FluxTable fluxTable : tables) {
            List<FluxRecord> records = fluxTable.getRecords();
            for (FluxRecord fluxRecord : records) {
                if (fluxRecord.getValueByKey("passing") != null) {
                    passing = Objects.requireNonNull(fluxRecord.getValueByKey("passing")).toString();
                } else if (fluxRecord.getValueByKey("total") != null) {
                    total = Objects.requireNonNull(fluxRecord.getValueByKey("total")).toString();
                }
            }
        }

        assert passing != null;
        assert total != null;

        return Double.parseDouble(passing)/Double.parseDouble(total);
    }

    public static Double toOneDouble(List<FluxTable> tables) {
        String sum = "0";

        for (FluxTable fluxTable : tables) {
            List<FluxRecord> records = fluxTable.getRecords();
            for (FluxRecord fluxRecord : records) {
                sum = Objects.requireNonNull(fluxRecord.getValue()).toString();
            }
        }

        return Double.parseDouble(sum);
    }

    public static Map<LocalDateTime, Double> toEach(List<FluxTable> tables) {
        Map<LocalDateTime, Double> each= new HashMap<>();
        ZoneId zoneId = ZoneId.systemDefault();

        for (FluxTable fluxTable : tables) {
            List<FluxRecord> records = fluxTable.getRecords();
            for (FluxRecord fluxRecord : records) {
                Instant instant = fluxRecord.getStop();
                assert instant != null;
                ZonedDateTime zonedDateTime = instant.atZone(zoneId);
                LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();
                each.put(localDateTime, (Double) fluxRecord.getValue());
            }
        }

        return each;
    }
}